/**
 * 分享板块公用js
 * 
 * @author Vernon.Chen
 * @date 2013-2-26
 */

$(function () {
    vote();
    addCommentEvent();
    upload();
    addShare();
    queryComment();
    searchTag();
    shareForward();
    deleteShare();
    checkGust();
    removeCommentEven();
    editShare();
    replayCommentor();
    lengthValidate();// 分享标题长度限制
});

var shareImageMaxSize = 3 ; // 实际是 4 - 1张

// 顶/踩
function vote () {
	// 顶
	$(".hand_up").bind("click", function() {
		if(DZQCheckForUser()){
			return false;
		}
        var $voteUp = $(this);
        var qid = $voteUp.data("qid");

		// 服务端+1
		var url = basePath + "share/shareAction!voteup.action" ;
        Wenda.post(url, {"qid": qid}, function (data) {
            if (data != null && data.message != null) {
                Wenda.alert(data.message, "提示消息", {
                    "确定": function () {
                        $(this).dialog("close");
                    }
                });
            } else {
                // 数值在客户端+1
                var vote = $voteUp.find("span").text();
                vote = parseInt(vote) + 1 ;
                $voteUp.find("span").text(vote);
                // 变样式
                $voteUp.removeClass("hand_up").addClass("hand_up_selected");
                $voteUp.unbind();
                // 获取踩的属性
                var $voteDn = $voteUp.next();
                $voteDn.removeClass("hand_down").addClass("hand_down_selected");
                $voteDn.unbind();
            }
        }, 'json');
	});
	
	// 踩
	$(".hand_down").bind("click", function() {
		if(DZQCheckForUser()){
			return false;
		}
		var $voteDn = $(this);
		var qid = $voteDn.data("qid");
		// 服务端+1
		var url = basePath + "share/shareAction!votedn.action" ;
        Wenda.post(url, {"qid": qid}, function (data) {
            if (data != null && data.message != null) {
                Wenda.alert(data.message, "提示消息", {
                    "确定": function () {
                        $(this).dialog("close");
                    }
                });
            } else {
                // 数值在客户端+1
                var vote = $voteDn.find("span").text();
                vote = parseInt(vote) + 1 ;
                $voteDn.find("span").text(vote);
                // 变样式
                $voteDn.removeClass("hand_down").addClass("hand_down_selected");
                $voteDn.unbind();
                // 获取踩的属性
                var $voteUp = $voteDn.prev();
                $voteUp.removeClass("hand_up").addClass("hand_up_selected");
                $voteUp.unbind();
            }
        }, 'json');
	});
}

// 添加分享评论
function addCommentEvent () {
	$(".creat_discuss_post").find("input[class='submit_input']").bind("click",function(){
		if(DZQCheckForUser() || isSubmit){
			return;
		}
		addComment($(this));
	});
}

// 添加评论
function addComment($this){
    var qid = $this.data("qid");
    var toUserId = $this.attr("toUid");
    var toUserName = $this.attr('toUserName');
    var textArea = $this.closest(".creat_discuss").find("textarea");
    var text = textArea.val();
	if($.trim(text).length == 0){
		Wenda.alert("请输入评论内容");
		return;
	}
	text = Wenda.removeConBefHtmlTags(text,"BR");//删除内容前面无用的标签
    var showText ;
    // 添加回复用户的名称
    if (toUserId > 0) {
        showText = '回复&nbsp;&nbsp;<a href="' + Constans.BASE_PATH + 'user/userAction!getUser.action?currentId=' + toUserId + '">' + toUserName + '</a> ' + text;
    } else {
        showText = text;
    }
	// 是否是匿名评论
	var isAnonymous = $this.parent().find("input[name='anonymous']:checked").length > 0 ? 1 : 0 ;
	//回复
	var params = {
			"comment.kid" : qid,
			"comment.content" : text,
			"question.title" : $this.data("title"),
			"question.id" : qid,
			"qid" : qid,
			"question.uid" : $this.data("uid"),
			"comment.anonymous" : isAnonymous,
			"comment.toUserId": toUserId,
			"comment.id":$this.attr("cid")
	};
	var req_url = basePath + "json/questionJsonAction!commentShare.action";
	
	Wenda.post(req_url, params, function(data) {
        if (data == null || data.comment == null) {// 直接返回
            return;
        }
        var commentId = data.comment.id;
		var appendHtml = "";
		// 评论数+1
		var comentObj = $('li[data-feed="' + qid + '"]').find("div.s_share_post span[name='commentCount']");
		var count = parseInt(comentObj.text()) ;
		if (count == 0) {
			appendHtml = '<ul class="s_discuss_list">' ;
		}
		// 直接在客户端做处理,如果是匿名,还得显示匿名
		appendHtml += '<li><div class="s_discuss_face">';
		if (isAnonymous == 1) { // 匿名
			appendHtml += '<img alt="匿名用户" src="' + Constans.IMG_BASE_URL +'s_' + USER_DEFAULT_IMG + '">' ;
		} else {
			appendHtml += '<a href="' + Constans.BASE_PATH + '"user/userAction!getUser.action?currentId="' + User.id + '"><img src="' + Constans.IMG_BASE_URL +'s_' + User.img + '"></a>' ;
		}
		appendHtml +=  '</div><div class="s_discuss_text">' ;
		if (isAnonymous == 1) {
			appendHtml += '<span>匿名用户</span>' ;
		} else {
			appendHtml += '<a class="name" href="' + Constans.BASE_PATH + 'user/userAction!getUser.action?currentId=' + User.id+ '">' + User.name + '</a>' ;
		}
		appendHtml += '<span>' + IM.replaceMsg(showText,true) + '</span><span>1秒前</span>'
				+ '<div class="fr">'
				+ '<a href="javascript:;" class="hideOrVisi" data-qid="' + qid + '" data-cid="' + commentId + '" name="remove-share-comment">删除评论</a>'
				+ '</div></div></li>' ;
		if (count == 0) {
			appendHtml += '</ul>' ;
		}
		if (count > 0 || comentObj.text() == "") {
			$this.closest("div.creat_discuss").next("ul.s_discuss_list").prepend(appendHtml) ;
		} else {
			$this.closest("div.creat_discuss").after(appendHtml);
		}
		comentObj.text( count + 1 );
		addCommentEvent(); // 还需重新绑定一下
		replayCommentor();
		removeCommentEven();
		if (data.messages != '') {
			Wenda.alert(data.messages);
			return;
		}
	}, 'json');
	textArea.val("");
}


// 上传
function upload () {
	$("#share_upload").bind("click",function(){
		if(DZQCheckForUser() || !checkAuth(DZQ_ACTIONS.INVITE_ANS)){
			return;
		}
		Wenda.openWin({
			loadUrl:Constans.BASE_PATH+"dialogCode.jsp #uploadImg",
			title:"上传图片",
			afterFun:function(){
				var $uploadImg = $("#uploadImg");
				$uploadImg.find("a[name='close']").click(function(){
					$("#modal-dialog").remove();
					$("div.modal-shadow").hide();
				});
				$uploadImg.find("a[name='upload']").click(function(){
					var url = document.getElementById("avt_file").value;
					if(!url || url.length == 0){
						Wenda.alert("请选择要上传的图片");
						return ;
					}
					$uploadImg.find("form").submit();
				});
			}
		});
	});
}

// 添加分享
function addShare(){
	$("#table_box_btns").find("input[data-name='save']").bind("click",function(){
		var $this = $(this) ;
		
		var ctype = $this.data("ctype"); // 类型
		if (ctype <= 0) { // 默认八卦分享
			ctype = 1 ;
		}
		// 初始化变量
		var title = $("#title").val();
		var content = "" ;
		var tag = "" ;
		var qid = $this.attr("qid");
		if (ctype == 1 || ctype == 4 || ctype == 5) { // 圈内八卦/机遇寻求
			if ($("#share-img").children().size() > 0) {
				var imgName = $("#share_upload_img").val() ;
				// 默认大图片
				content = imgName ;
			}
		}  else { // 资料分享/物料供求
			content = shareContent.html();
			content = Wenda.removeConBefHtmlTags(content, "BR"); // 去掉没有用的BR
		}
		//if (ctype == 2 || ctype == 3) { // 资料分享/物料供求
			tag = $("#addQ_tags").val() ;
		//}
		if(title=="" || title == null){
			Wenda.alert("分享标题不能为空");
			return;
		}
		
		// 是否是匿名发布
		var isAnonymous = $this.parent().find("input[name='anonymous']:checked").length > 0 ? 1 : 0 ;
		var postData = {
				"question.title" : title,
				"question.content" : content,
				"question.tag" :tag,
				"question.id":qid,
				"ctype":ctype,
				"isAnonymous":isAnonymous
		} ;
		
		var url = Constans.BASE_PATH + "json/questionJsonAction!addShare.action" ;
		if(qid){
			url = Constans.BASE_PATH + "json/questionJsonAction!updateQuestion.action" ;
		}
		Wenda.post(url, postData, function(data) {
			WendaAsk.isSubmit = false;
			if (data.isLogin == 'no') {
				window.onbeforeunload = null;
				window.location.href = Constans.BASE_PATH + "login.jsp";
				return;
			}
			if (data.messages != null && data.messages != '') {
				Wenda.alert(data.messages);
				return;
			}
			var questionId = data.question.id;
			if (questionId > 0) {// 分享添加成功
				window.location.href = Constans.BASE_PATH + "share/shareAction!success.action?ctype=" + ctype + "&qid=" + questionId;
			}
		},'json');
	});
}

// 查看评论
function queryComment() {
    $("div.s_share_post").find("a[class='s_discuss']").bind("click", function () {
        // 查询出
        var $this = $(this);
        var postData = null;
        if ($this.data("type") == 'list') { // 查询的列表数==10
            postData = {
                "qid": $this.data("qid"),
                "disPlayFlag": $this.data("type")
            };
        } else {
            postData = {
                "qid": $this.data("qid")
            };
        }
        if ($this.parent().next("div.s_discuss_div").length > 0) {
            $this.parent().next("div.s_discuss_div").toggle();
        } else {
            Wenda.post(Constans.BASE_PATH + "question/question!fetchComments.action", postData, function (data) {
                $this.parent().after(data);
                $this.parent().next().find("a[name='collapse']").bind("click", function () {
                    $(this).closest(".s_discuss_div").hide();
                });
                addCommentEvent();
                removeCommentEven();
                replayCommentor();
            }, 'html');
        }
    });
}

// 推荐的话题
function searchTag (){
	//效果不好，先注释掉，by chang
//	$("#title").bind("focusout",function() {
//		var $this = $(this);
//		var ctype = $this.data("ctype");
//		var tagStr = "" ;
//		if (ctype == 2 || ctype == 3) { // 需要推荐话题
//			var keyword = $this.val(); 
//			Wenda.post(Constans.BASE_PATH + "json/searchJsonAction!sugTagByQuestion.action", {"keyword":keyword, "type":ctype},function(data){
//				if (data != null && data.tagSuggestionItems != null) {
//					var index = 0 ;
//					for ( var i = 0; i < data.tagSuggestionItems.length; i++) {
//						if (data.tagSuggestionItems[i] != null) {
//							if (index == 5) {
//								break ;
//							}
//							tagStr += data.tagSuggestionItems[i].name + " ";
//							index ++ ;
//						}
//					}
//				}
//				$("#addQ_tags").val(tagStr);
//			}, 'json');
//		}
//	});
}


// 分享转发

function shareForward () {
	$("a[name='share-forward']").bind("click", function() {
		var $this = $(this) ;
		var $content =     $this.data("title")   ;
		var opts = {
			type:"weibo",
			content:$content,
			title:"分享转发",
			qid:$this.data("qid")
		} ;
		new DzqShare(opts);
		setTimeout(function(){ // 隐藏邮件分享,圈内分享
			$("#tb-webshare-letter").parent().hide();
			$("#tb-webshare-email").parent().hide();
		},1000);
	});
	
}

// 设置UPloadAction返回回来的图片地址
function setImgSrc(imgName) {
    window.setTimeout(function () {
        if (imgName != null && imgName.length > 0) {
            if ($('#share-img').find('li').size() > shareImageMaxSize) {//检查数量是否已经过4张
                alert("图片张数最大为" + (shareImageMaxSize + 1));
                return;
            }
            var lastContent = $("#share_upload_img").val() + '<img src="' + Constans.IMG_BASE_URL + imgName + '"/>';
            $("#share_upload_img").val(lastContent); // 赋值
            var url = Constans.IMG_BASE_URL + imgName;
            var mid_img_url = Constans.IMG_BASE_URL + 'l_' + imgName;
            var imgHtml = [
                '<li class="ui-widget-content ui-draggable">',
                '   <img src="' + mid_img_url + '" img = "' + imgName + '" data-src="' + url + '">',
                '   <div class="icon_btn_div">',
                '       <a class="ui-icon ui-icon-zoomin fr" title="大图" href="javascript:;" data-src="' + url + '" onclick="javascript:viewLargerImage($(this));">大图</a>',
                '       <a class="ui-icon ui-icon-trash" title="删除" href="javascript:;" onclick="javascript:shareRemoveImage($(this).closest(\'li\'))" >删除</a>',
                '   </div>',
                '</li>'
            ].join('');
            $("#share-img").append(imgHtml);
            // 关闭弹出层
            $("#modal-dialog").css("display", "none");
            $("div.modal-shadow").hide();
        } else {
            alert("图片上传失败");
        }
    }, 100);
}

function shareRemoveImage($item) {
    var imgId = $item.find("img").attr("data-id");
    $item.fadeOut(function () {
        $item.remove();
        // 将最新的图片DOM给重新赋值
        var lastContent = '';
        $('#share-img li').find('img').each(function () {
            lastContent += '<img src="' + $(this).data('src') + '"/>'
        });
        $("#share_upload_img").val(lastContent); // 赋值
    });
}

// 删除分享
function deleteShare() {
    $("a[name='question_remove']").bind("click", function () {
        var $this = $(this);
        var $q_uid = $("#q_uid");
        var ctype = $this.data("ctype");
        if ($q_uid.val() == User.id) {// 自己删除
            Wenda.alert("确定要删除该分享吗？", "", {
                "取消": function () {
                    $(this).dialog("close");
                    return;
                },
                "确定": function () {
                    Wenda.post(basePath + "json/qdetailJsonAction!deleteQuestion.action", {
                        "qid": $this.data("qid")
                    }, function (data) {
                        window.location.href = basePath + "share/shareAction!allShare.action?ctype=" + ctype;
                    });
                }
            });
        } else { // 管理员删除
            Wenda.openWin({
                loadUrl: Constans.BASE_PATH + "dialogCode.jsp #questiondeletemsgDiv",
                title: "删除分享",
                afterFun: function () {
                    $("#lable").text($("#qname").val());// 收件人
                    var $msgContent = $("#msgContent");
                    $("#closefeed").click(function () {
                        Wenda.closeWin();
                        return;
                    });
                    $("#sendmsg").click(function () {
                        var postData = {
                            "qid": $this.data("qid"),
                            "messages": $msgContent.val()
                        };
                        Wenda.post(basePath + "json/qdetailJsonAction!deleteQuestion.action", postData, function (data) {
                            window.location.href = basePath + "share/shareAction!allShare.action?ctype=" + ctype;
                        });
                    });
                }
            });
        }
    });
}

// 删除分享评论
function removeCommentEven() {
    $("a[name='remove-share-comment']").bind("click", function () {
        var $this = $(this);
        var qid = $this.data("qid");
        var postData = {
            "qid": qid,
            "cid": $this.data("cid")
        };
        // 让用户确定是否真的删除
        Wenda.alert("确定要删除吗？", "", {
            "取消": function () {
                $(this).dialog("close");
                return;
            },
            "确定": function () {
                Wenda.post(basePath + "json/qdetailJsonAction!removeQuestionComment.action", postData, function (data) {
                    if (data.message == true) {
                        // 删除评论
                        $this.closest('li').hide(500);
                        // 数值在客户端-1
                        var commentCount = $('li[data-feed="' + qid + '"]').find('span[name="commentCount"]').text();
                        commentCount = parseInt(commentCount) - 1;
                        $('li[data-feed="' + qid + '"]').find('span[name="commentCount"]').text(commentCount);
                    } else {
                        window.location.href = Question.curWinHref;
                    }
                });
                $(this).dialog("close");
                return;
            }
        });
    });
}

// 游客拦截
function checkGust () {
	$(".share_creat_button").bind("click", function() {
		if(DZQCheckForUser() || !checkAuth(DZQ_ACTIONS.INVITE_ANS)){
			return;
		}
		// 提交请求
		window.location.href = $(this).data("url") ;
	});
}
/**
 * 编辑分享
 */
function editShare(){
	$("#editshare").each(function(){
		if(utype == 4 || utype == 3){
			$(this).show();
			$(this).click(function(){
				$("#my_question_form").show();
				$("div.s_share_list").hide();
			});
		}
	});
}

/**
 * 回复评论者
 */
function replayCommentor(){
	$("a[name=comment_replay]").click(function(){
		var el=$(this),t=el.closest(".s_discuss_div"),r=".replydiv",b=".submit_input",_h = [];
		_h.push("<div class='replydiv' style='background: #eff6fa;padding: 1px 10px 0;border-radius: 30px;text-decoration: none;margin: 0 5px 5px 0;display: inline-block;'>");
		_h.push("回复&nbsp;&nbsp;"+el.attr("uname"));
		_h.push("&nbsp;&nbsp;<span style='cursor:pointer;cursor:hand;' title='取消回复' class='cancel'><strong>x</strong></span>");
		_h.push("</div>");
		t.find(r).length>0&&t.find(r).remove();
		t.find(b).attr({
			toUid:el.attr("uid"),
			cid:el.attr("data-cid"),
            toUserName:el.attr("uname")
		});
		t.prepend(_h.join(""));
		t.find("span.cancel").click(function(){
			t.find(r).remove();
			t.find(b).removeAttr("toUid cid toUserName");
		});
	});
}

/**
 * 标题长度限制
 */
function lengthValidate () {
    DZQUtil.inputWCnt("#title","#title-length-tip",lengthRange.shareTitle.input_max);
}